﻿#define PORT_SELF 8888  //本机端口号宏定义

#include "udpwidget.h"
#include "ui_udpwidget.h"

#include <QHostAddress>
#include <QString>
#include <QDebug>
UdpWidget::UdpWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UdpWidget)
{
    ui->setupUi(this);

    portSelf    =   ui->lEdt_portSelf->text().toInt();
    setWindowTitle(QString("UDP通信测试（端口号:%1）").arg(portSelf));

    //分配空间，指定父对象
    udpSocket   =   new QUdpSocket(this);
    //UDP套接字绑定本机端口号
    //udpSocket->bind(portSelf);
    //对方发送数据触发槽函数
    connect(udpSocket,&QUdpSocket::readyRead,this,&UdpWidget::dealReadInfo);
}

UdpWidget::~UdpWidget()
{
    delete ui;
}

void UdpWidget::dealReadInfo()
{
    //读取对方发送过来的内容
    char buf[1024]={0};
    QHostAddress peerAddr;
    quint16 peerPort;
    qint64 len_msg  =   udpSocket->readDatagram(buf,sizeof (buf),&peerAddr,&peerPort);
    if(len_msg > 0)
    {
        QString str = QString("[%1:%2:]%3").arg(peerAddr.toString()).arg(peerPort).arg(buf);
        ui->txtEdt_info->append(str);
        setWindowTitle(QString("UDP通信测试（端口号:%1）").arg(portSelf));
    }

}
void UdpWidget::on_btn_send_clicked()
{
    //获取对方IP地址和端口号
    QString ip  =   ui->lEdt_IP->text();
    qint16 port =   ui->lEdt_port->text().toInt();
    //获取编辑区内容
    QString str =   ui->txtEdt_info->toPlainText();

    //给指定的IP地址和端口发送数据
    udpSocket->writeDatagram(str.toUtf8(),QHostAddress(ip),port);
}

void UdpWidget::on_btn_close_clicked()
{
    if(ui->btn_close->text()=="关闭通信")
    {
        qDebug()<<"位置1";
        if(udpSocket->isOpen())
        {
            qDebug()<<"位置2";    //结论:UDP端口断开方式有待考量
            //udpSocket->close();
            ui->btn_close->setText("开启通信");
            udpSocket->leaveMulticastGroup(QHostAddress("224.0.0.2"));//离开
            qDebug()<<"位置3";
        }
    }
    else
    {
        qDebug()<<"位置4";
        if(udpSocket->isOpen()==false)
        {
            qDebug()<<"位置5";
            //udpSocket->open();//开启模式需要设置
            ui->btn_close->setText("关闭通信");
        }
    }

}

void UdpWidget::on_btn_setPort_clicked()
{
    portSelf    =   ui->lEdt_portSelf->text().toInt();

    //200518组播时添加
    udpSocket->bind(QHostAddress::AnyIPv4,portSelf);

    setWindowTitle(QString("UDP通信测试（端口号:%1）").arg(portSelf));

    //200518加入某个组播地址
    //组播为D类地址
    udpSocket->joinMulticastGroup(QHostAddress("224.0.0.2"));
    //udpSocket->leaveMulticastGroup(QHostAddress("224.0.0.2"));//离开
}
